package org.yinxue.spider.web.controller.admin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.yinxue.spider.core.model.ATag;
import org.yinxue.spider.core.spider.Spider;
import org.yinxue.spider.domain.entities.SeedUrl;
import org.yinxue.spider.domain.entities.SpiderUrlInfo;
import org.yinxue.spider.domain.repositories.SeedUrlRepository;
import org.yinxue.spider.domain.repositories.SpiderRepository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 自定义url控制层<br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-12 15:14
 * @since 1.0.0
 */
@Controller
@RequestMapping("/seedUrls")
public class SeedUrlController {

    @Resource
    private SeedUrlRepository seedUrlRepository;

    @Resource
    private SpiderRepository spiderRepository;

    @GetMapping("index")
    public String index(){
        return "custom/index";
    }

    @GetMapping("")
    @ResponseBody
    public List<SeedUrl> list() {
        return seedUrlRepository.findAll();
    }

    @PostMapping("")
    @ResponseBody
    public String add(@RequestParam(name = "url") String url) {
        SeedUrl seedUrl = new SeedUrl();
        seedUrl.setUrl(url);
        seedUrl.set4Create();
        seedUrlRepository.save(seedUrl);
        return "OK";
    }

    @PutMapping("/{id}")
    @ResponseBody
    public SeedUrl modify(@PathVariable Long id) {
        SeedUrl seedUrl  = seedUrlRepository.findById(id).get();
        seedUrlRepository.save(seedUrl);
        return seedUrl;
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public String delete(@PathVariable Long id) {
        seedUrlRepository.deleteById(id);
        return "OK";
    }
    @PostMapping("/deleteAll")
    @ResponseBody
    public String deleteAll(){
        seedUrlRepository.deleteAll();
        return "OK";
    }

    @PostMapping("/deleteSelected")
    @ResponseBody
    public String deleteSelected(@RequestBody List<SeedUrl> seedUrls){
        seedUrlRepository.deleteAll(seedUrls);
        return "OK";
    }


    @PostMapping("/{id}/spider")
    @ResponseBody
    public String spider(@PathVariable Long id) {
        SeedUrl seedUrl = seedUrlRepository.findById(id).get();
        List<ATag> aTags = new Spider().parseATag(seedUrl.getUrl());
        for (ATag aTag : aTags) {
            SpiderUrlInfo spiderUrlInfo = new SpiderUrlInfo();
            spiderUrlInfo.setUrl(aTag.getUrl());
            spiderUrlInfo.setUrlTitle(aTag.getText());
            spiderUrlInfo.setSpiderUrl(seedUrl.getUrl());
            spiderUrlInfo.set4Create();
            spiderRepository.save(spiderUrlInfo);
        }
        seedUrl.setSpiderCount(seedUrl.getSpiderCount() + 1);
        seedUrl.setUpdateTime(new Date());
        seedUrlRepository.save(seedUrl);
        return "成功爬取" + aTags.size() + "条记录";
    }
}
